import 'dart:async';
import 'dart:convert';

import 'package:flutter/material.dart';
import 'package:flutter_app/bean/file_path_entity.dart';
import 'package:flutter_app/manager/AppSetInfoManager.dart';
import 'package:flutter_app/manager/UserInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/network/UploadFilesUtils.dart';
import 'package:flutter_app/utils/DialogUtils.dart';
import 'package:flutter_app/utils/EventBusUtils.dart';
import 'package:flutter_app/utils/image_file_info_utils.dart';
import 'package:flutter_app/utils/prevent_tap_utils.dart';
import 'package:flutter_app/utils/sp_utils.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:flutter_app/values/CommonParam.dart';
import 'package:flutter_app/widget/watermark/watermark_utils.dart';
import 'package:get/get.dart';
import 'package:image_pickers/image_pickers.dart';

import '../../WebViewPage.dart';
import 'problem_report_state.dart';

class ProblemReportLogic extends GetxController {
  final ProblemReportState state = ProblemReportState();

  late TextEditingController titleCon, contentCon;

  // 要上传的文件
  List<Media> imagesList = [];

  @override
  void onInit() {
    super.onInit();
    titleCon = TextEditingController();
    contentCon = TextEditingController();
    initImageModel();
  }

  /// 初始化 从首页带过来的图片
  void initImageModel() async {
    if (Get.arguments != null) {
      imagesList.add(Get.arguments);
      updateData();
      update();
    } else {
      String? json = await sp.getString(CommonParam.SP_PROBLEM_REPORT + UserInfoManager().getUserId());
      if (json != null) {
        Map map = jsonDecode(json);
        titleCon.text = map["title"];
        contentCon.text = map["content"];
        List<dynamic> list = map["list"];
        if (list.length > 0) {
          List<ImageFileInfo> imageFileInfo = list.map((e) => ImageFileInfo.fromJson(e)).toList();
          List<Media> medias = ImageFileInfoUtils().listImageFileInfoToListMedia(imageFileInfo);
          imagesList.addAll(medias);
        }
        update();
      }
    }
  }

  @override
  void onReady() {
    super.onReady();
    WatermarkUtils().addWatermark(Get.context!, UserInfoManager().getUserName());
  }

  /// 保存随手拍填报信息
  Future<void> saveOtherProblemSubmit() async {
    if (PreventTapUtils().multiTouch()) {
      return;
    }
    if (imagesList.length == 0) {
      return toast.show("请添加图片或者视频");
    }
    if (titleCon.text.isEmpty) {
      return toast.show("请填写标题");
    }
    if (contentCon.text.isEmpty) {
      return toast.show("请填写详细说明");
    }
    if (!state.isSelected.value) {
      return toast.show("请阅读并同意《随手拍问题上报注意事项》注意事项");
    }
    List<FilePathEntity> filePathEntity = await UploadFilesUtils().upload(imagesList);
    if (filePathEntity.length == 0) {
      return;
    }
    if (imagesList.length != filePathEntity.length) {
      dialogUtils.show(
        context: Get.context!,
        title: "提示",
        content: "文件未全部上传，重新尝试？",
        callbackOk: () {
          saveOtherProblemSubmit();
        },
      );
      return;
    }
    Map<String, dynamic> param = {
      "content": contentCon.text,
      "title": titleCon.text,
      "fileList": filePathEntity,
    };
    ResultData resultData = await Api.saveOtherProblemSubmit(param);
    if (resultData.isSuccess) {
      toast.show(resultData.data["message"]);
      bus.fire(DynamicEvent());
      deleteData();
      Get.back();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  bool isOnWillPop() {
    return titleCon.text.isNotEmpty || contentCon.text.isNotEmpty || imagesList.length > 0;
  }

  goToWebViewPage() {
    Get.to(() => WebViewPage(title: '随手拍问题上报注意事项', url: AppSetInfoManager().getFilmUrl(),));
  }

  Timer? timer; // 计时器

  int start = 1; // ？ 之后进行保存

  // 更新数据
  void updateData() {
    if (timer != null) {
      timer!.cancel();
    }
    const oneSec = Duration(seconds: 1);
    timer = Timer.periodic(oneSec, (Timer timer) {
      if (start == 0) {
        timer.cancel();
        /// 距离上次更新 需要超过一秒之后 才保存数据  防止 sp多次无效调用
        Map<String, dynamic> map = {
          "title": titleCon.text,
          "content": contentCon.text,
          "list": ImageFileInfoUtils().listMediaToListImageFileInfo(imagesList),
        };
        sp.setString(CommonParam.SP_PROBLEM_REPORT + UserInfoManager().getUserId(), jsonEncode(map));

      } else {
        start--;
      }
    });
  }

  // 删除数据
  void deleteData() {
    sp.remove(CommonParam.SP_PROBLEM_REPORT + UserInfoManager().getUserId());
  }

  @override
  void onClose() {
    super.onClose();
    WatermarkUtils().removeWatermark();
    if (timer != null) {
      timer!.cancel();
      timer = null;
    }
  }
}
